package com.inno.subject.domain.strategy.subject;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.inno.subject.common.enums.IsDeletedFlagEnum;
import com.inno.subject.common.error.BusinessException;
import com.inno.subject.common.utils.DateUtils;
import com.inno.subject.domain.entity.SubjectAnswerBO;
import com.inno.subject.domain.entity.SubjectInfoBO;
import com.inno.subject.domain.entity.SubjectTypeBO;
import com.inno.subject.domain.service.SubjectTypeDomainService;
import com.inno.subject.infra.basic.entity.PlannerSubjectAnswer;
import com.inno.subject.infra.basic.entity.PlannerSubjectInfo;
import com.inno.subject.infra.basic.service.PlannerSubjectAnswerService;
import com.inno.subject.infra.basic.service.PlannerSubjectInfoService;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.TransactionStatus;

import java.util.List;

/**
 * @author shenzeyang
 */
@Component
public class ChoiceSubjectHandler implements SubjectHandler {
    @Resource
    private SubjectTypeDomainService subjectTypeDomainService;
    @Resource
    private  PlannerSubjectAnswerService plannerSubjectAnswerService;
    @Resource
    private PlannerSubjectInfoService plannerSubjectInfoService;
    private Long subjectType;

    @PostConstruct
    public void init() {
        subjectType = querySubjectType().getId();
    }
    @Override
    public Long getTypeId() {
        return this.subjectType;
    }

    @Override
    public void handle(SubjectInfoBO subjectInfoBO, PlannerSubjectInfo entity) {
        // answer_option是正确选项   answer_content是所有选项内容
        subjectInfoBO.setId(entity.getId());
        PlannerSubjectAnswer plannerSubjectAnswer = this.builderSubjectAnswer(subjectInfoBO);
        plannerSubjectAnswerService.insert(plannerSubjectAnswer);
        this.saveSubject(plannerSubjectInfoService,entity);
    }

    @Override
    public SubjectTypeBO querySubjectType() {
        List<SubjectTypeBO> subjectTypeBOList = subjectTypeDomainService.queryList();
        return subjectTypeBOList
                .stream()
                .filter(subjectTypeBO -> "选择题".equals(subjectTypeBO.getTypeName()))
                .findFirst()
                .orElseThrow(() -> new IllegalArgumentException("cannot init this class because current type(选择题) not found. please check your datasource! "));
    }
}
